package com.etc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.etc.dao.UserMapper;
import com.etc.model.Result;
import com.etc.model.User;
import com.etc.model.esuser;
import com.etc.service.UserService;
import com.etc.utils.EsUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequestBuilder;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;



@Service
@Slf4j
public class UserServiceImpl implements UserService {
    TransportClient client = EsUtil.getEs();


    @Autowired
    private UserMapper userMapper;

    @Override
    public Result findByUsername(User user, HttpServletRequest request) {
        Result<User> result = new Result<>();
        HttpSession session = request.getSession();
        String randomString = (String) session.getAttribute("randomString");
        if (randomString != null && !"".equals(randomString)){
            if (randomString.equalsIgnoreCase(user.getVerify())){
                //判断user 用户名 密码 验证码 是否为空
                if(user == null || "".equals(user.getUsername()) || "".equals(user.getPassword())){
                    result.setStatus(400);
                    result.setMessage("用户名或者密码为空");
                }
                //根据用户名查询
                List<User> byUsername = userMapper.findByUsername(user.getUsername());
                //判断list集合是否为空并且这个集合里面是否有参数
                if(byUsername != null && !byUsername.isEmpty()) {
                    //拿出下标为0的用户赋给user1
                    User user1 = byUsername.get(0);
                    //判断页面传过来的参数跟数据库里面的数据是否一致
                    if (user1.getPassword().equals(user.getPassword())) {
                        result.setStatus(200);
                        result.setMessage("success");
                        result.setData(user1);
                    }else {
                        result.setStatus(500);
                        result.setMessage("密码错误");
                    }
                }
            }else {
                result.setStatus(600);
                result.setMessage("验证码错误");
            }
        }
        return result;
    }

    @Override
    public List<User> userByAll() {
        return userMapper.userByAll();
    }


    @Override
    public Integer save(User user) throws IOException {



        IndexResponse indexResponse = client.prepareIndex("wangcc", "usdsaer", user.getId()).setSource(jsonBuilder().startObject()
                .field("username", user.getUsername())
                .field("age", user.getPassword())
                .endObject()).get();
        //状态
        RestStatus status = indexResponse.status();
        client.close();
        return status.getStatus();
    }

    @Override
    public Integer delete(String id) {
        DeleteResponse response = client.prepareDelete("wangcc", "usdsaer", id).get();
        RestStatus status = response.status();
        return status.getStatus();
    }

    @Override
    public Integer update(User user) throws Exception {
        UpdateRequest request = new UpdateRequest();
        request.index("wangcc");
        request.type("usdsaer");
        request.id(user.getId());
        request.doc(
                jsonBuilder()
                        .startObject()
                        .field("username",user.getUsername())
                        .field("age",user.getPassword())
                        .endObject());
        UpdateResponse updateResponse = client.update(request).get();
        RestStatus status = updateResponse.status();
        return status.getStatus();
    }

    @Override
    public esuser select(String id) {
//        GetResponse response = client.prepareGet("wangcc", "usdsaer", id).get();
//        String sourceAsString = response.getSourceAsString();
//        System.out.println(sourceAsString);
//        esuser user = JSON.parseObject(sourceAsString, esuser.class);


        JSONObject resultObject = null;
        SearchResponse searchResponse = client.prepareSearch("wangcc")
                .setSearchType(SearchType.DEFAULT)
                // 实际返回的数量为5*index的主分片个数
                .setSize(5)
                // 这个游标维持多长时间
                .setScroll(TimeValue.timeValueMinutes(8)).execute().actionGet();
        // 第一次查询，只返回数量和一个scrollId
        System.out.println(searchResponse.getScrollId());
        System.out.println(searchResponse.getHits().getTotalHits());
        System.out.println(searchResponse.getHits().hits().length);
        System.out.println("------------------------------");
        // 使用上次的scrollId继续访问
        do {
            int num = scanData(client, searchResponse.getScrollId());
            if (num == 0) break;
        } while (true);
        System.out.println("------------------------------END");

        return null;
    }



    private int scanData (Client esClient, String scrollId){
        SearchResponse searchResponse = esClient.prepareSearchScroll(scrollId)
                .setScroll(TimeValue.timeValueMinutes(8)).execute().actionGet();
        System.out.println(searchResponse.getScrollId());
        System.out.println(searchResponse.getHits().getTotalHits());
        int num = searchResponse.getHits().hits().length;
        System.out.println(searchResponse.getHits().hits().length);
        JSONObject resultObject = null;
        for (SearchHit hit : searchResponse.getHits()) {
            String json = hit.getSourceAsString();
            try {
//                resultObject = new JSONObject(json);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return num;
    }

}
